package com.example.demo.interceptor;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.example.demo.arithmetic.annotation.ResponseHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Description: 全局响应转换<br/>
 *
 * @author Sender<br                                                                                                                                                                                                                                                               />;
 * @taskId <br/>
 * <br/>
 */
@Slf4j
@RestControllerAdvice(basePackages = { "com.example.demo.web" })
public class GlobalResponseResolver implements ResponseBodyAdvice<Object> {
    /**
     * 是否应用响应处理，方法包含注解@ResponseHandler的进行处理
     *
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        log.info(" Current method : {} supports response handler {}.", methodParameter.getMethod().getName(),
                methodParameter.getMethod().isAnnotationPresent(ResponseHandler.class));
        return methodParameter.getMethod().isAnnotationPresent(ResponseHandler.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
            ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(o);
            // 对称AES加密
            byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            return aes.encryptHex(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return o;
    }
}
